<?php

namespace App\Models;

use App\Models\BaseModel;

use Illuminate\Filesystem\Filesystem;

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Response\QrCodeResponse;

class Goods extends BaseModel
{

    protected $guarded = [];

    protected $casts = [
        "goods_class_path" => "json",
        'created_at' => 'Y-m-d H:i:s',
    ];

    protected $with = ['images'];

    protected $appends = [];

    /**
     * 产品销售属性列表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function attr_map()
    {
        return $this->hasMany(GoodsAttrMap::class, 'goods_id')
            ->with([
                'attr.values',
                'value_map',
                'value_map.attr_value',
            ]);
    }

    public function attr_value_map()
    {
        return $this->hasMany(GoodsAttrValueMap::class, 'goods_id');
    }

    /**
     * 产品 SKU
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function skus()
    {
        return $this->hasMany(GoodsSku::class, 'goods_id')->with(['stock', 'attrs']);
    }

    /**
     * 产品 库存列表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function stock()
    {
        return $this->hasMany(GoodsSkuStock::class, 'goods_id');
    }

    /**
     * 产品详情内容关联
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function content()
    {
        return $this->hasOne(GoodsContent::class);
    }

    /**
     * 产品分类关联
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function goodsClass()
    {
        return $this->belongsTo(GoodsClass::class);
    }

    /**
     * 产品品牌管理
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }

    /**
     * 产品图片关联
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function images()
    {
        return $this->hasMany(GoodsImage::class);
    }

    /**
     * 产品兑换信息关联
     * @return \Illuminate\Database\Eloquent\Relations\hasOne
     */
    public function exchange()
    {
        return $this->hasOne(GoodsExchange::class);
    }

    /**
     * 产品预览二维码管理
     * @return \Illuminate\Database\Eloquent\Relations\hasOne
     */
    public function qrcode()
    {
        return $this->hasOne(GoodsQrcode::class);
    }

    /**
     * 产品封面字段
     * @param $key
     * @return mixed
     */
    public function getCoverAttribute($key)
    {
        return collect($this->images)->first();
    }

    protected static function boot()
    {
        parent::boot();
        self::deleting(function ($model) {
            $model->content()->delete();
            $model->stock()->delete();
            $model->skus()->delete();
            $model->attr_map()->delete();
            $model->attr_value_map()->delete();
            $model->images()->delete();
            $model->exchange()->delete();
        });

        static::saved(function ($model) {
            if ($model->id)
            {
                $qrcode = GoodsQrcode::where('goods_id', $model->id)->first();
                if (!$qrcode)
                {
                    $store_path = storage_path('app/public/goods/');
                    $file = new Filesystem();
                    if (!$file->exists($store_path) )
                    {
                        $file->makeDirectory($store_path, 0777, true, true);
                    }

                    $name = $model->id . '.png';
                    $code = env('EASYWECHAT_DELEGATION_HOST').'/pages/product/detail?id='.$model->id;
                    $qrCode = new QrCode($code);
                    $qrCode->setSize(300);
                    $qrCode->setWriterByName('png');
                    $qrCode->setEncoding('UTF-8');
                    $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH());
                    $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
                    $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
                    $qrCode->setValidateResult(false);

                    $qrCode->setRoundBlockSize(false);
                    $qrCode->setMargin(10);
                    // $dataUri = $qrCode->writeDataUri();
                    $qrCode->writeFile($store_path.'/'.$name);
                    $qrcode_url = 'goods/' . $name;

                    \App\Models\GoodsQrcode::query()
                        ->where('goods_id', $model->id)
                        ->updateOrCreate([], [
                            'goods_id' => $model->id,
                            'qrcode' => $qrcode_url
                        ]);
                }
            }
        });

    }

    /**
     * 商品列表
     *
     * @param  array $attributes [description]
     * @return [type]             [description]
     */
    public static function getList(array $attributes)
    {
        extract($attributes);

        $where = ['putaway' => 1];

        $model = self::where($where);

        if (!empty($brand))
        {
            $model->where('brand_id', intval($brand));
        }

        if (!empty($category))
        {
            $model->where('goods_class_id', intval($category));
        }

        if (isset($keyword) && trim($keyword))
        {
            $keyword = trim($keyword);
            $keyword = strip_tags($keyword);
            $model->where(function ($query) use ($keyword) {
                $query->where('name', 'like', '%' . strip_tags($keyword) . '%');
            });
        }

        $total = $model->count();

        $model->orderBy('id', 'DESC');

        $model->with(['skus', 'exchange']);

        if (isset($per_page))
        {
            $data = $model->paginate($per_page)->toArray();

            return self::formatBody(['list' => $data['data'], 'paged' => self::formatPaged($page, $per_page, $total)]);
        }
        else
        {
            $data = $model->get()->toArray();

            return self::formatBody(['list' => $data]);
        }
    }

    /**
     * 商品详情
     *
     * @param  goods_id
     */
    public static function getInfo(array $attributes)
    {
        extract($attributes);

        $model = Goods::where(['putaway' => 1, 'id' => $goods_id]);

        $data = $model->with(['skus', 'exchange', 'content'])->first();

        $product_data = $data->toArray();$product_data = $data->toArray();

        return self::formatBody(['product' => $product_data]);
    }


}
